import 'package:flutter/material.dart';
import 'package:canteen/class/ingredient.dart';
import 'package:canteen/edit_c_v.dart';
import 'package:vibration/vibration.dart';
import 'package:canteen/constants.dart';

class AddIngredientPage extends StatefulWidget {
  static String id = 'add_ingredient_page';

  @override
  State<AddIngredientPage> createState() => _AddIngredientPageState();
}

class _AddIngredientPageState extends State<AddIngredientPage> {
  TextEditingController nameEditingController = TextEditingController();
  TextEditingController numEditingController = TextEditingController();
  int option = 0;

  bool isAddNeeded = false;
  String selectedUnit = '';
  List<String> units = ['斤', '千克', '克', '毫升', '升','个','只','粒','份','条','勺','包','瓶','根'];

  void addIngredient() {
    if (nameEditingController.text.isEmpty &&
        numEditingController.text.isEmpty) {
      setState(() {
        isAddNeeded = !isAddNeeded;
      });
      return;
    }
    ingredientString = '';
    Ingredient ingredient = Ingredient(
        type: ingredientOptions[option],
        unit: selectedUnit,
        name: nameEditingController.text);
    setState(() {
      dish.components.addEntries(
          [MapEntry(ingredient, double.parse(numEditingController.text))]);
    });
    refreshIngredient();
    clearTextField();
  }

  void refreshIngredient() {
    List<String> tempR = [];
    dish.components.forEach((key, value) {
      tempR.add('${key.type} ${key.name} ${value} ${key.unit}');
    });
    ingredientString = tempR.join('#');
  }

  void clearTextField() {
    setState(() {
      nameEditingController.clear();
      numEditingController.clear();
    });
  }

  void triggerVibration() async {
    // 检查设备是否支持震动
    bool canVibrate = await Vibration.hasVibrator() ?? false;
    if (canVibrate) {
      // 触发一次短震动
      Vibration.vibrate(duration: 100);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    selectedUnit = units[0];
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    nameEditingController.dispose();
    numEditingController.dispose();
  }

  void removeIngredient(ingredientEntry) {
    setState(() {
      dish.components.remove(ingredientEntry.key);
      refreshIngredient();
    });
    triggerVibration();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffbfbfb),
      appBar: AppBar(
        backgroundColor: Color(0xffffffff).withOpacity(0.89),
        elevation: 0,
        centerTitle: true,
        title: Text(
          '原料',
          style: TextStyle(color: Colors.black, fontSize: 16),
        ),
        actions: [
          GestureDetector(
            onTap: () {
              if (isAddNeeded) {
                setState(() {
                  isAddNeeded = false;
                });
                return;
              }
              addIngredient();
            },
            child: Icon(
              isAddNeeded
                  ? Icons.add_circle_outline_rounded
                  : Icons.check_circle_outline,
              color: Color(0xff6486f3),
            ),
          ),
          SizedBox(
            width: 10,
          )
        ],
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_rounded,
            color: Colors.black,
          ),
        ),
      ),
      body: Column(
        children: [
          ...ingredientOptions
              .map(
                (e) => Expanded(
                  child: Container(
                    margin: EdgeInsets.symmetric(horizontal: 30),
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            Container(
                              margin: EdgeInsets.only(right: 10),
                              width: 15,
                              height: 15,
                              decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: Color(0xffc80815)),
                            ),
                            Text(e),
                          ],
                        ),
                        Expanded(
                          child: AnimatedSwitcher(
                            duration: Duration(milliseconds: 200),
                            child: GridView.builder(
                              key: ValueKey(dish.components.length),
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisSpacing: 10,
                                mainAxisSpacing: 10,
                                crossAxisCount: 3,
                              ),
                              itemCount: dish.components.keys
                                  .toList()
                                  .where((element) => element.type == e)
                                  .toList()
                                  .length,
                              itemBuilder: (context, index) {
                                var ingredientEntry = dish.components.entries
                                    .where((element) => element.key.type == e)
                                    .elementAt(index);
                                return GestureDetector(
                                  onLongPress: () {
                                    removeIngredient(ingredientEntry);
                                  },
                                  child: Container(
                                    padding: EdgeInsets.symmetric(
                                        vertical: 5, horizontal: 8),
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(15),
                                        color: Colors.white,
                                        boxShadow: [
                                          BoxShadow(
                                            offset: Offset(0, 2),
                                            blurRadius: 4,
                                            color: Colors.black.withOpacity(0.2),
                                          )
                                        ]),
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Row(
                                          children: [
                                            Text(
                                              '${ingredientEntry.key.name}',
                                              style: TextStyle(fontSize: 15),
                                            )
                                          ],
                                        ),
                                        Expanded(
                                          child: Row(
                                            children: [
                                              Container(
                                                width: 2,
                                                margin: EdgeInsets.only(
                                                    right: 8, top: 6, bottom: 4),
                                                decoration: BoxDecoration(
                                                    color: Colors.black),
                                              ),
                                              Expanded(
                                                child: Column(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment
                                                          .spaceEvenly,
                                                  children: [
                                                    Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      children: [
                                                        Text(
                                                          '类型',
                                                          style: TextStyle(
                                                              color: Colors.grey,
                                                              fontSize: 12),
                                                        ),
                                                        Text(
                                                          '${ingredientEntry.key.type}',
                                                          style: TextStyle(
                                                              color: Colors.black,
                                                              fontSize: 12),
                                                        )
                                                      ],
                                                    ),
                                                    Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      children: [
                                                        Text(
                                                          '数量',
                                                          style: TextStyle(
                                                              color: Colors.grey,
                                                              fontSize: 12),
                                                        ),
                                                        Text(
                                                          '${ingredientEntry.value}',
                                                          style: TextStyle(
                                                              color: Colors.black,
                                                              fontSize: 12),
                                                        )
                                                      ],
                                                    ),
                                                    Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      children: [
                                                        Text(
                                                          '单位',
                                                          style: TextStyle(
                                                              color: Colors.grey,
                                                              fontSize: 12),
                                                        ),
                                                        Text(
                                                          '${ingredientEntry.key.unit}',
                                                          style: TextStyle(
                                                              color: Colors.black,
                                                              fontSize: 12),
                                                        )
                                                      ],
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              )
              .toList(),
          AnimatedSwitcher(
            transitionBuilder:
                (Widget child, Animation<double> animation) {
              return SizeTransition(
                child: child,
                sizeFactor: animation,
              );
            },
            duration: Duration(milliseconds: 150),
            child: isAddNeeded
                ? SizedBox()
                : Container(
              key: ValueKey(isAddNeeded),
                    margin: EdgeInsets.symmetric(horizontal: 30, vertical: 20),
                    padding: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(15),
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            offset: Offset(1, 2),
                            blurRadius: 4,
                            color: Colors.black.withOpacity(0.3),
                          )
                        ]),
                    child: Column(
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.baseline,
                          textBaseline: TextBaseline.alphabetic,
                          children: [
                            Text(
                              '材料:',
                              style: TextStyle(fontSize: 16),
                            ),
                            Expanded(
                              child: TextField(
                                maxLength: 5,
                                controller: nameEditingController,
                                decoration: const InputDecoration(
                                  counterText: '',
                                  isDense: true,
                                  contentPadding: EdgeInsets.zero,
                                  border: InputBorder.none,
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.baseline,
                          textBaseline: TextBaseline.alphabetic,
                          children: [
                            Text(
                              '数量:',
                              style: TextStyle(fontSize: 16),
                            ),
                            Expanded(
                              child: TextField(
                                maxLength: 5,
                                controller: numEditingController,
                                decoration: const InputDecoration(
                                  counterText: '',
                                  isDense: true,
                                  contentPadding: EdgeInsets.zero,
                                  border: InputBorder.none,
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '单位:',
                              style: TextStyle(fontSize: 16),
                            ),
                            DropdownButton(
                                isDense: true,
                                elevation: 1,
                                borderRadius: BorderRadius.circular(15),
                                menuMaxHeight: 150,
                                underline: SizedBox(),
                                icon: SizedBox(),
                                value: selectedUnit,
                                items: units
                                    .map(
                                      (e) => DropdownMenuItem(
                                        value: e,
                                        child: Text(
                                          e,
                                          style: TextStyle(
                                              color: Color(0xff2b3d85),
                                              fontSize: 12),
                                        ),
                                      ),
                                    )
                                    .toList(),
                                onChanged: (value) {
                                  setState(() {
                                    selectedUnit = value!;
                                  });
                                })
                          ],
                        ),
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 8),
                          height: 0.5,
                          color: Colors.black.withOpacity(0.5),
                        ),
                        AnimatedSwitcher(
                          duration: Duration(milliseconds: 200),
                          child: Row(
                            key: ValueKey(option),
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: ingredientOptions
                                .asMap()
                                .entries
                                .map(
                                  (entry) => GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        option = entry.key;
                                      });
                                    },
                                    child: Row(
                                      children: [
                                        Text(entry.value),
                                        option == entry.key
                                            ? Icon(
                                                Icons.circle,
                                                color: Color(0xff6486f3),
                                              )
                                            : Icon(
                                                Icons.circle_outlined,
                                                color: Colors.black,
                                              ),
                                      ],
                                    ),
                                  ),
                                )
                                .toList(),
                          ),
                        )
                      ],
                    ),
                  ),
          ),
        ],
      ),
    );
  }
}
